import 'dart:async';
import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/User.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/GlobalEvent.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/utils/sp_utils.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/view/mine/setting/view_email.dart';
import 'package:flutter_chip/widget/RouteSlide.dart';
import 'package:fsuper/fsuper.dart';
import 'package:provide/provide.dart';
import 'package:sharesdk_plugin/sharesdk_defines.dart';
import 'package:sharesdk_plugin/sharesdk_interface.dart';

///设置
class SettingPage extends StatefulWidget {
  @override
  _SettingPageState createState() => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {
  User user;

  //动画
  CancelFunc closeLoading;

  @override
  Widget build(BuildContext context) {
    user = Provide.value<User>(context);
    return Scaffold(
      appBar: AppBar(
        elevation: 0.0,
        centerTitle: true,
        automaticallyImplyLeading: true,
        backgroundColor: Theme.of(context).cardColor,
        title: Text('设置', style: TextStyle(fontSize: 18)),
      ),
      body: CustomScrollView(slivers: <Widget>[
        SliverToBoxAdapter(child: SizedBox(height: 8)),
        _emailWidget(),
        SliverToBoxAdapter(child: Divider(height: 1)),
        _phoneWidget(),
        SliverToBoxAdapter(child: Divider(height: 1)),
        _passwordWidget(),
        SliverToBoxAdapter(child: SizedBox(height: 8)),
        _thirdWidget("qq"),
        SliverToBoxAdapter(child: Divider(height: 1)),
        _thirdWidget("wx"),
        SliverToBoxAdapter(child: Divider(height: 1)),
        _thirdWidget("sina"),
        SliverToBoxAdapter(child: SizedBox(height: 8)),
        _aboutWidget(),
        SliverToBoxAdapter(child: SizedBox(height: 20)),
        buildLoginButton(),
        SliverToBoxAdapter(child: SizedBox(height: 40)),
      ]),
    );
  }

  ///邮箱
  Widget _emailWidget() {
    bool isBind = null != user && null != user.email;
    return SliverToBoxAdapter(
      child: FSuper(
        backgroundColor: Colors.white,
        width: double.maxFinite,
        height: 48,
        padding: EdgeInsets.only(left: 10, right: 10),
        text: "邮箱",
        textSize: 16,
        textAlignment: Alignment.centerLeft,
        child1: Text(
          isBind ? user.email : "未设置",
          style: TextStyle(color: Colors.grey),
        ),
        child1Alignment: Alignment.centerRight,
        child1Margin: EdgeInsets.only(right: 10),
        onChild1Click: () {
          if (isBind) {
            showMsgDialog(context, "email");
          } else {
            Navigator.of(context).push(RouteSlide(EmailPage()));
          }
        },
      ),
    );
  }

  ///手机号
  Widget _phoneWidget() {
    bool isBind = null != user && null != user.phone;
    return SliverToBoxAdapter(
      child: FSuper(
        width: double.infinity,
        height: 48,
        text: "手机号",
        textAlignment: Alignment.centerLeft,
        textSize: 16,
        backgroundColor: Colors.white,
        padding: EdgeInsets.only(left: 10, right: 10),
        child1: Text(
          isBind ? user.phone : "未设置",
          style: TextStyle(color: Colors.grey),
        ),
        child1Alignment: Alignment.centerRight,
        child1Margin: EdgeInsets.only(right: 10),
        onClick: () {
          if (!isBind) {
            Routers.router.navigateTo(
                context, "${Routers.PAGE_CHECKPHONE}?title=bdsj",
                transition: TransitionType.inFromRight);
          } else {
            showMsgDialog(context, "phone");
          }
        },
      ),
    );
  }

  ///修改密码
  Widget _passwordWidget() {
    return SliverToBoxAdapter(
      child: FSuper(
        backgroundColor: Colors.white,
        width: double.maxFinite,
        height: 48,
        padding: EdgeInsets.only(left: 10, right: 10),
        textAlignment: Alignment.centerLeft,
        text: "修改账号密码",
        textSize: 16,
        onClick: () {
          if (null == user || null == user.phone) {
            Toast.show("请先绑定手机号");
            return;
          }
          Routers.router.navigateTo(context,
              "${Routers.PAGE_CHECKPHONE}?title=xgmm&phone=${user.phone}",
              transition: TransitionType.inFromRight);
        },
      ),
    );
  }

  ///三方账号
  Widget _thirdWidget(String type) {
    String id;
    String text;
    switch (type) {
      case "qq":
        id = null != user ? user.qqId : null;
        text = "QQ";
        break;
      case "wx":
        text = "微信";
        id = null != user ? user.wxId : null;
        break;
      default:
        text = "微博";
        id = null != user ? user.wbId : null;
        break;
    }

    String status = null != id && id.isNotEmpty ? "已绑定" : "未绑定";
    return SliverToBoxAdapter(
        child: FSuper(
      width: double.infinity,
      height: 48,
      text: text,
      textAlignment: Alignment.centerLeft,
      textSize: 16,
      backgroundColor: Colors.white,
      padding: EdgeInsets.only(left: 10, right: 10),
      child1: Text(status, style: TextStyle(color: Colors.grey)),
      child1Alignment: Alignment.centerRight,
      child1Margin: EdgeInsets.only(right: 10),
      onClick: () {
        if ("未绑定" == status) {
          _thirdBind(context, type);
        } else {
          showMsgDialog(context, type);
        }
      },
    ));
  }

  ///关于我们
  Widget _aboutWidget() {
    return SliverToBoxAdapter(
        child: FSuper(
      width: double.infinity,
      height: 48,
      text: "关于我们",
      textAlignment: Alignment.centerLeft,
      textSize: 16,
      backgroundColor: Colors.white,
      padding: EdgeInsets.only(left: 10, right: 10),
      child1: Image.asset(Comm.IMG_ARROW_RIGHT, width: 18, height: 18),
      child1Alignment: Alignment.centerRight,
      child1Margin: EdgeInsets.only(right: 10),
      onClick: () {
        Routers.router.navigateTo(context, Routers.PAGE_ABOUT,
            transition: TransitionType.inFromRight);
      },
    ));
  }

  ///信息提示对话框
  void showMsgDialog(BuildContext context, String type) {
    String msg;
    if (type == "qq") {
      msg = "确定要解绑QQ？";
    } else if (type == "wx") {
      msg = "确定要解绑微信？";
    } else if (type == 'phone') {
      msg = "您确定要换绑手机号吗？";
    } else if (type == "email") {
      msg = "确定要换绑邮箱？";
    }
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("温馨提示"),
            content: Text(msg, style: TextStyle(fontSize: 16)),
            actions: <Widget>[
              FlatButton(
                child: Text("取消"),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
              FlatButton(
                child: Text("确定"),
                onPressed: () {
                  Navigator.pop(context);
                  if (type == 'phone') {
                    Routers.router.navigateTo(context,
                        "${Routers.PAGE_CHECKPHONE}?title=bdsj&phone=${user.phone}",
                        transition: TransitionType.inFromRight);
                  } else if (type == "email") {
                    Navigator.of(context).push(
                      RouteSlide(EmailPage(email: user.email)),
                    );
                  } else {
                    _unbindAccount(type);
                  }
                },
              ),
            ],
          );
        });
  }

  ///退出登录按钮
  Widget buildLoginButton() {
    return SliverToBoxAdapter(
      child: Offstage(
        offstage: null == user || null == user.userId,
        child: Container(
          height: 40,
          margin: EdgeInsets.only(left: 80, right: 80),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(6),
              border:
                  Border.all(width: 1, color: Theme.of(context).accentColor)),
          child: FlatButton(
            child: Text(
              '退出当前账号',
              style:
                  TextStyle(color: Theme.of(context).accentColor, fontSize: 18),
            ),
            onPressed: () {
              _loginOut();
            },
          ),
        ),
      ),
    );
  }

  void _thirdBind(BuildContext context, String type) {
    ShareSDKPlatform platforms;
    if (type == "qq") {
      platforms = ShareSDKPlatforms.qq;
    } else if (type == "wx") {
      platforms = ShareSDKPlatforms.wechatSession;
    } else if (type == "sina") {
      platforms = ShareSDKPlatforms.sina;
    }
    closeLoading = Toast.loading("绑定中...");
    SharesdkPlugin.getUserInfo(platforms,
        (SSDKResponseState state, Map user, SSDKError error) {
      print("登录结果：$user");
      if (state == SSDKResponseState.Success) {
        if (null != user && user.containsKey("dbInfo")) {
          _updateUser(json.decode(user["dbInfo"]), type);
        }
      } else if (state == SSDKResponseState.Cancel) {
        if (null != closeLoading) {
          closeLoading();
        }
        Toast.show("操作已取消");
      } else {
        if (null != closeLoading) {
          closeLoading();
        }
        Toast.show("绑定失败");
      }
    });
  }

  ///更新用户信息
  void _updateUser(Map map, String type) async {
    if (null == user) {
      return;
    }
    Map<String, String> params = Map();
    if (type == "qq") {
      params['qqId'] = map["userID"];
    } else if (type == "wx") {
      params['wxId'] = map["userID"];
    } else {
      params['wbId'] = map["userID"];
    }
    if (null != user && (null == user.imgUrl || user.imgUrl.isEmpty)) {
      params['imgUrl'] = map["icon"];
    }
    if (null != user && (null == user.sex || user.sex.isEmpty)) {
      params['sex'] = map["gender"] == "0" ? "男" : "女";
    }

    Http.post(Api.URL_USER_UPDATE, params: params, successCallBack: (data) {
      SpUtils.put(SpUtils.SP_USER, data);
      setState(() {
        user.update(User.fromJson(json.decode(data)));
      });
      Toast.show("绑定成功");
      if (null != closeLoading) {
        closeLoading();
      }
    }, errorCallBack: (error) {
      Toast.show(error);
      if (null != closeLoading) {
        closeLoading();
      }
    });
  }

  ///解绑
  void _unbindAccount(String type) async {
    if (null == user) {
      return;
    }
    if (null == user.phone) {
      Toast.show("为防止账号丢失，请先绑定手机号");
      return;
    }
    closeLoading = Toast.loading("解绑中...");
    Map<String, String> params = Map();
    if (type == "qq") {
      params['qqId'] = "";
    } else if (type == "wx") {
      params['wxId'] = "";
    } else {
      params['wbId'] = "";
    }
    Http.post(Api.URL_USER_UPDATE, params: params, successCallBack: (data) {
      SpUtils.put(SpUtils.SP_USER, data);
      setState(() {
        user.update(User.fromJson(json.decode(data)));
      });
      Toast.show("解绑成功");
      if (null != closeLoading) {
        closeLoading();
      }
    }, errorCallBack: (error) {
      Toast.show(error);
      if (null != closeLoading) {
        closeLoading();
      }
    });
  }

  ///退出登录
  Future _loginOut() async {
    closeLoading = Toast.loading("正在退出...");
    Http.get(Api.URL_LOGINT_OUT, successCallBack: (data) {
      if (null != closeLoading) {
        closeLoading();
      }
      Toast.show("退出成功");
      SpUtils.clear();
      user.update(User());
      GlobalEvent().eventBus.destroy();
      Routers.router.navigateTo(context, Routers.PAGE_LOGIN,
          transition: TransitionType.inFromRight, replace: true);
    }, errorCallBack: (data) {
      if (null != closeLoading) {
        closeLoading();
      }
      Toast.show(data);
    });
  }
}
